

import com.example.onlineeducation.net.HttpResponse
import com.example.onlineeducation.net.HttpResponseList
import com.example.onlineeducation.net.HttpResponsePageList
import com.example.onlineeducation.net.HttpVersionResponse
import com.yc.jetpacklib.data.constant.YcNetErrorCode
import com.yc.jetpacklib.data.entity.YcDataSourceEntity
import com.yc.jetpacklib.exception.YcException
import com.yc.jetpacklib.extension.ycIsEmpty
import com.yc.jetpacklib.mapper.IMapper

/**
 * SimpleDes:
 * Creator: Sindi
 * Date: 2021-02-19
 * UseDes:
 */


/**
 * 获取非空的data(用于服务端返回成功，但数据为空情况)
 */
fun <T> HttpVersionResponse<T?>.ycGetDataNoNull(): T {
    return data ?: throw YcException("data数据为空", YcNetErrorCode.DATE_NULL_ERROR)
}

/**
 * 获取非空的data(用于服务端返回成功，但数据为空情况)
 */
fun <T> HttpResponse<T?>.ycGetDataNoNull(): T {
    return data ?: throw YcException("data数据为空", YcNetErrorCode.DATE_NULL_ERROR)
}

/**
 * 分页列表数据判空处理（总页数）
 */
fun <T, R> HttpResponsePageList<T>.pageListToDataSource(map: IMapper<T, R>): YcDataSourceEntity<R> {
    return when {
        result == null || result.dataList.ycIsEmpty() -> YcDataSourceEntity(null, 0)
        else -> {
            val dataModel = result.dataList!!.map {
                map.map(it)
            }
            YcDataSourceEntity(dataModel, result.totalPage ?: 0)
        }
    }
}

/**
 * 普通列表数据判空处理（拿所有数据）
 */
fun <T, R> HttpResponseList<T>.listToIMapper(map: IMapper<T, R>): List<R>? {
    return when {
        dataList.ycIsEmpty() -> null
        else -> {
            dataList!!.map {
                map.map(it)
            }
        }
    }
}

